<script setup>
import { ref } from 'vue';
let commodities = ref
(
  [
    { name: '金华火腿', price: 1499, count: 2 },
    { name: '垃圾袋', price: 10, count: 3 },
    { name: '苹果手机', price: 10000, count: 1 },
    { name: '电动剃须刀', price: 50, count: 1 }
  ]
)
function delCommodity(index) {
  commodities.value.splice(index, 1) 
}
function allTotal() {
  let total = 0
  for (let i = 0; i < commodities.value.length; i++) {
    total += commodities.value[i].price * commodities.value[i].count
  }
  return total
}
</script>

<template>
<div>
  <h1>购物车</h1>
   <table>
  <tr>
    <th>序号</th>
    <th>商品名称</th>
    <th>商品价格</th>
    <th>数量</th>
    <th>小计</th>
    <th>操作</th>
  </tr>
  <tr v-for="(commodity, index) in commodities">
    <td>{{ index + 1 }}</td>
    <td>{{ commodity.name }}</td> 
    <td>{{ commodity.price }}</td>
    <td>{{ commodity.count }}</td>
    <td>{{ commodity.price * commodity.count }}</td>
    <td><button v-on:click="delCommodity(index)">删除</button></td>
  </tr>
  <tr>
    总计：{{ allTotal() }}
  </tr>
 </table>
</div>
</template>


<style scoped>
table {
  border-collapse: collapse;
  width: 80%;
  margin: 20px auto;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px 12px;
  text-align: left;
}

th {
  background-color: #f5f5f5;
}

button {
  background-color: #ff4444;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 3px;
  cursor: pointer;
}

button:hover {
  background-color: #cc0000;
}
</style>
